//@ts-nocheck
import {TEXT,ELEMENT} from './constants';
import {onlyOne,setProps} from './util';

export function createDOM(element){
  element = onlyOne(element); // emmm todo
  const {$$typeof} = element;
  let dom = null;
  if(!$$typeof){ // element 是一个字符串或则数字 ReactDOM.render(123,document.getElementById('root'))
    dom = document.createTextNode(element);
  }else if($$typeof === TEXT){
    dom = document.createTextNode(element.content);
  }else if($$typeof === ELEMENT){
    dom = createNativeDOM(element);
  }
  return dom;
}

function createNativeDOM(element){
  const {type, props} = element;
  const dom = document.createElement(type); // 真实的BUTTON DOM对象
  // 1. 创建此虚拟DOM节点的子节点
  createNativeDOMChildren(dom, element.props.children);
  setProps(dom, props);
  // 2. 给此DOM元素添加属性
  return dom;
}

function createNativeDOMChildren(parentNode, children){
  children && children.flat(Infinity).forEach(child=>{
    const childDOM = createDOM(child); // 创建此虚拟DOM节点的真实DOM元素
    parentNode.appendChild(childDOM);
  })
}

export function ReactElement($$typeof, type, key, ref, props) {
  const element = {
    $$typeof, type, key, ref, props
  };
  return element;
}
